package com.yupi.springbootinit.neo4j;

import com.yupi.springbootinit.model.entity.Relationship;
import org.neo4j.driver.*;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class RelationRepository {

    private final Driver driver;

    public RelationRepository(Driver driver) {
        this.driver = driver;
    }

    // 1. 查询所有关系
    public List<Relationship> selectAll() {
        String query = "MATCH (start:my_entity)-[relation]->(end:my_entity) RETURN TYPE(relation) AS text, ID(end) AS to, ID(start) AS from";
        return runQuery(query);
    }

    // 2. 查询指定关系类型为 "属于" 的关系
    public List<Relationship> selectBelong() {
        String query = "MATCH p=()-[r:`属于`]->() RETURN p LIMIT 25";
        return runQuery(query);
    }

    // 3. 根据名称查询相关节点
    public List<Relationship> selectRelatedNode(String name) {
        String query = String.format("MATCH (start:my_entity) WHERE start.name CONTAINS '%s' MATCH (start)-[r]->(end) RETURN TYPE(r) AS text, ID(end) AS to, ID(start) AS from", name);
        return runQuery(query);
    }

    // 4. 查询名称匹配的根节点相关关系
    public List<Relationship> selectRelatedRootNode(String name) {
        String query = String.format("MATCH (end:my_entity) WHERE end.name CONTAINS '%s' MATCH (start)-[r]->(end) RETURN TYPE(r) AS text, ID(end) AS to, ID(start) AS from", name);
        return runQuery(query);
    }

    // 5. 查询两个名称的相关节点
    public List<Relationship> selectRelatedNode(String startName, String endName) {
        String query = String.format("MATCH (start:my_entity) WHERE start.name CONTAINS '%s' MATCH (start)-[r]-(end:my_entity) WHERE end.name CONTAINS '%s' RETURN TYPE(r) AS text, ID(end) AS to, ID(start) AS from", startName, endName);
        return runQuery(query);
    }

    // 运行查询并将结果转换为 Relationship 列表
    private List<Relationship> runQuery(String query) {
        List<Relationship> relationships = new ArrayList<>();

        try (Session session = driver.session()) {
            Transaction transaction = session.beginTransaction();
            Result result = transaction.run(query);

            while (result.hasNext()) {
                Record record = result.next();
                String text = record.get("text").asString();
                long from =  record.get("from").asLong();
                long to = record.get("to").asLong();

                relationships.add(new Relationship(text, from, to));
            }

            transaction.commit();
        }

        return relationships;
    }
}
